﻿using System;
using System.Web;
using ErrorDumper.PropertyExtracting;

namespace ErrorDumper.Web.PropertyExtractors {
    public class HttpExceptionPropertyBinder : IExceptionPropertyExtractor {

        public void ExtractProperties(object instance, ExceptionPropertyCollection properties) {
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (properties == null)
                throw new ArgumentNullException("properties");

            var exception = instance as HttpException;
            if (exception == null)
                return;

            Write(properties, "HttpErrorCode", exception.GetHttpCode);
        }

        private static void Write<T>(ExceptionPropertyCollection properties, string name, Func<T> resolver) {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");
            if (properties.Contains(name))
                return;
            string value;
            try { value = Convert.ToString(resolver()); }
            catch { return; }
            if (!string.IsNullOrWhiteSpace(value))
                properties[name] = value;
        }
    }
}